package datamodel

import (
	"time"
)

var waitCount int
var waitOverCount int

//WaitLocker 保持当前使用的元素不被替代的队列
type WaitLocker struct {
	timeOut  chan bool
	flag     bool
	timer    *time.Timer
	timsSpan int
}

//Init 初始化
func (_this *WaitLocker) Init(millisecond int) {
	waitCount = 0
	waitOverCount = 0
	_this.timeOut = make(chan bool)
	_this.timsSpan = millisecond
	_this.timer = time.NewTimer(time.Millisecond * time.Duration(_this.timsSpan))
}

//Wait 等待
func (_this *WaitLocker) Wait() bool {
	_this.timer.Reset(time.Millisecond * time.Duration(_this.timsSpan))
	_this.flag = true
	res := false
	select {
	// 一直没有从ch中读取到数据，但从timeout中读取到了数据
	case res = <-_this.timeOut:
		break
	case <-_this.timer.C:
		res = false
	}
	_this.flag = false
	return res
}

//Done 继续执行
func (_this *WaitLocker) Done() {
	if _this.flag {
		if _this.timer != nil {
			_this.timer.Stop()
		}
		_this.timeOut <- false
	}
}

//Close 关闭释放资源
func (_this *WaitLocker) Close() {
	close(_this.timeOut)
}
